/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * DataViewer.java
 *
 * Created on Oct 24, 2009, 2:38:19 PM
 */
package wekinator;

import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.table.TableColumn;
import wekinator.Plog.Msg;
import wekinator.util.Util;

/**
 *
 * @author rebecca
 */
public class DataViewer extends javax.swing.JFrame {

    SimpleDataset myDataset = null;
    private javax.swing.JTable table;
    private DataTableModel model;

    public DataViewer(SimpleDataset dataset) {
        initComponents();
        myDataset = dataset;
        populateTable(dataset);
    // this.gui = gui;
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        scrollTable = new javax.swing.JScrollPane();
        buttonDone = new javax.swing.JButton();
        buttonDelete = new javax.swing.JButton();
        buttonAdd = new javax.swing.JButton();
        buttonListen = new javax.swing.JButton();
        buttonListen1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        buttonDone.setText("Done");
        buttonDone.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonDoneActionPerformed(evt);
            }
        });

        buttonDelete.setText("Delete selected");
        buttonDelete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonDeleteActionPerformed(evt);
            }
        });

        buttonAdd.setText("Add row");
        buttonAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonAddActionPerformed(evt);
            }
        });

        buttonListen.setText("Listen");
        buttonListen.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonListenActionPerformed(evt);
            }
        });

        buttonListen1.setText("Save to ARFF...");
        buttonListen1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonListen1ActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(scrollTable, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 628, Short.MAX_VALUE)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                .add(buttonDelete)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(buttonAdd)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(buttonListen)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 67, Short.MAX_VALUE)
                .add(buttonListen1)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(buttonDone))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(scrollTable, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 411, Short.MAX_VALUE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(buttonDone)
                    .add(buttonDelete)
                    .add(buttonAdd)
                    .add(buttonListen)
                    .add(buttonListen1)))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void buttonDoneActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonDoneActionPerformed
        if (WekinatorRunner.isLogging()) {
            Plog.log(Msg.DATA_VIEWER_DONE);
        }
        this.dispose();

    }//GEN-LAST:event_buttonDoneActionPerformed

    private void buttonDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonDeleteActionPerformed
        int rs[] = table.getSelectedRows();
        model.deleteRows(table.getSelectedRows());
        if (WekinatorRunner.isLogging()) {
            Plog.log(Msg.DATA_VIWER_DELETE_SELECTED, "numDel=" + rs.length);
        }
        table.repaint();
}//GEN-LAST:event_buttonDeleteActionPerformed

    private void buttonAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonAddActionPerformed
        model.addRow();
        if (WekinatorRunner.isLogging()) {
            Plog.log(Msg.DATA_VIEWER_ADD_ROW);
        }
}//GEN-LAST:event_buttonAddActionPerformed

    private void buttonListenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonListenActionPerformed

        if (table.getSelectedRow() == -1) {
            return;
        }


        int row = table.getSelectedRow();
        double d[] = model.getSelectedParams(row);
        for (int i = 0; i < d.length; i++) {
            Double dd = new Double(d[i]);
            if (dd.isNaN()) {
                d[i] = WekinatorLearningManager.getInstance().getParams(i);
            }
        }
        //gui.listenToValues(f);
        WekinatorLearningManager.getInstance().setParams(d);

        OscHandler.getOscHandler().startSound();
        //OscHandler.getOscHandler().sendParamsToSynth(d); //TODO: Want dist
         OscHandler.getOscHandler().packageDistAndSendParamsToSynth(d);
        if (WekinatorRunner.isLogging()) {
            Plog.log(Msg.DATA_VIEWER_LISTEN);
        }
}//GEN-LAST:event_buttonListenActionPerformed

    private void buttonListen1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonListen1ActionPerformed
        /*try {
            File file = findArffFileToSave();
            if (file != null) {
                myDataset.writeInstancesToArff(file);
            }
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, ex.getMessage(), "Invalid feature configuration", JOptionPane.ERROR_MESSAGE);
        } */
        if (myDataset != null) {

        File file = Util.findSaveFile("arff",
                "arff file",
                SimpleDataset.getDefaultLocation(),
                this);
        if (file != null) {
            try {
                myDataset.writeInstancesToArff(file);
                if (WekinatorRunner.isLogging()) {
                    Plog.log(Msg.DATA_VIEWER_SAVE_ARFF_BUTTON, file.getAbsolutePath() + "/" + file.getName());
                }
                Util.setLastFile(SimpleDataset.getFileExtension(), file);
            } catch (Exception ex) {
                Logger.getLogger(DataViewer.class.getName()).log(Level.INFO, null, ex);
                JOptionPane.showMessageDialog(this, ex.getMessage(), "Could not save to file", JOptionPane.ERROR_MESSAGE);
            }
        }
    }
    }//GEN-LAST:event_buttonListen1ActionPerformed

    private File findArffFileToSave() throws IOException {
        return null;
    //TODOTODOTODO: handle this after get fileext support in.
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {

                boolean isDiscrete[] = {true, false};
                int numVals[] = {3, 3};
                //String featureNames[] = {"F1", "f2", "F3", "f4", "f5"};
                String featureNames[] = new String[100];
                for (int i = 0; i < featureNames.length; i++) {
                    featureNames[i] = "F" + i;
                }
                String paramNames[] = {"P1", "p2"};
                SimpleDataset s = new SimpleDataset(featureNames.length, 2, isDiscrete, numVals, featureNames, paramNames);


                new DataViewer(s).setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton buttonAdd;
    private javax.swing.JButton buttonDelete;
    private javax.swing.JButton buttonDone;
    private javax.swing.JButton buttonListen;
    private javax.swing.JButton buttonListen1;
    private javax.swing.JScrollPane scrollTable;
    // End of variables declaration//GEN-END:variables

    private void populateTable(SimpleDataset data) {
        model = new DataTableModel(data);
        table = new JTable(model);
        setTableColumns();
        table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        scrollTable.setViewportView(table);

        table.repaint();
    }

    private void setTableColumns() {
        // table.getColumnModel().get
        table.getColumnModel().getColumn(0).setPreferredWidth(30);
        table.getColumnModel().getColumn(1).setPreferredWidth(40);
        table.getColumnModel().getColumn(2).setPreferredWidth(100);
        for (int i = 3; i < table.getColumnCount(); i++) {
            TableColumn c = table.getColumnModel().getColumn(i);
            c.setPreferredWidth(50);
            c.setMinWidth(20);

            c.setResizable(true);

        }
    }
}

